package com.starview.star.operators.pio.runtime;

import java.nio.channels.*;

import com.starview.platform.data.IValue;
import com.starview.platform.data.IFunction;
import com.starview.platform.data.EvaluationException;
import com.starview.platform.data.value.Factory;


public class StarCompletionHandler<T> implements CompletionHandler<T, IFunction>
{
  private IValueConverter<T> cv;
  private IValue errorId;

  private static IValue noError = Factory.newString("");

  public StarCompletionHandler(IValueConverter<T> cv, IValue errorIndicator) {
    this.cv = cv;
    this.errorId = errorIndicator;
  }

  static public <T> IFunction checkCallbackFunction(IValue v)
  {
    IFunction callback = (IFunction)v;
    // TODO: Check arity, types?!
    return callback;
  }

  static public void completed(IValue result, IFunction att) {
    try {
      att.enter(result, noError);
    } catch (EvaluationException e) {
    }
  }
  
  @Override
  public void completed(T result, IFunction att) {
    completed(cv.convert(result), att);
  }

  public static void failed(IValue errorResult, Throwable t, IFunction att) {
    try {
      att.enter(errorResult, Factory.newString(t.getMessage()));
    } catch (EvaluationException e) {
    }
  }

  @Override
  public void failed(Throwable t, IFunction att) {
    failed(this.errorId, t, att);
  }
};
